package com.opennews.openplatform.controller;

import com.opennews.openplatform.myspringbootcore.dto.ApiResponse;
import com.opennews.openplatform.myspringbootmvccore.controller.GeneralGlobalExceptionHandler;
import lombok.RequiredArgsConstructor;
import org.jooq.exception.IntegrityConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.Map;

@RequiredArgsConstructor
@ControllerAdvice
public class GlobalExceptionHandler extends GeneralGlobalExceptionHandler {
    @ExceptionHandler(IntegrityConstraintViolationException.class)
    public ResponseEntity<ApiResponse<Map>> handleIntegrityConstraintViolationException() {
        return httpResponseHelper.getErrorResponse(HttpStatus.CONFLICT, Map.ofEntries(
                Map.entry("message", "Data integrity constraint violated.")
        ));
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResponseEntity<ApiResponse<Map>> handleDataIntegrityViolationException() {
        return httpResponseHelper.getErrorResponse(HttpStatus.CONFLICT, Map.ofEntries(
                Map.entry("message", "Data integrity constraint violated. Check for conflicting data.")
        ));
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResponseEntity<ApiResponse<Map>> handleDuplicateKeyException() {
        return httpResponseHelper.getErrorResponse(HttpStatus.CONFLICT, Map.ofEntries(
                Map.entry("message", "Duplicate key error. This data already exists.")
        ));
    }
}
